﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.Text;

namespace vroom.wcf.service.message.util
{
	public class endpointMessageInspector : IClientMessageInspector
	{
		public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
		{
			// Implement this method to inspect/modify messages after a message
			// is received but prior to passing it back to the client 
			var messageBodyReader = reply.GetReaderAtBodyContents();
			var messageBody = messageBodyReader.ReadOuterXml();
			double msgSize = DetermineAndLogMessageDiagnostics(messageBody);
			

			Console.WriteLine("AfterReceiveReply called, size:" + msgSize + ", Encoder:" + reply.Properties.Encoder);
		}

		public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
		{
			// Implement this method to inspect/modify messages before they 
			// are sent to the service
			Console.WriteLine("BeforeSendRequest called");
			return null;
		}

		private double DetermineAndLogMessageDiagnostics(string messageBody)
		{
			double bodySizeInBytes = Encoding.UTF8.GetByteCount(messageBody);
			return bodySizeInBytes / 1024;
		}  
	} 
}
